package org.pp.core;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.exceptions.JWTDecodeException;
import jakarta.servlet.http.HttpServletRequest;
import org.pp.entity.PpUser;
import org.pp.service.IPpUserService;
import org.pp.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.Serializable;
import java.util.Map;
import java.util.Objects;

@Component
public class MiniappSessionUtil {

    private static IPpUserService userService;

    @Autowired
    public void  setUserService(IPpUserService userService){
        MiniappSessionUtil.userService=userService;
    }

    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static Long getUserId(){
       return getUserId(true);
    }

    public static Long getUserId(boolean throwable){
        HttpServletRequest request = getRequest();
        String token= request.getHeader(MiniappConstants.tokenHeader);
        if(StrUtil.isBlank(token)){
            if(throwable){
                throw BizErro.TOKEN_EXPIRE.erro();
            }else{
                return null;
            }
        }
        try {
            //jwt去获的用户id
            Map<String, Object> payload = JwtUtil.getPayload(token);
            Object value = payload.get(MiniappConstants.jwtLoginKey);
            if(Objects.isNull(value)){
                throw BizErro.TOKEN_EXPIRE.erro();
            }
            //id没有超过long的话，value就是int,超过了Integer.MAX_VALUE,value就是long
            PpUser user = userService.getById((Serializable) value);
            if(Objects.isNull(user)||!Objects.equals(user.getStatus(),MiniappConstants.statusActive)){
                throw BizErro.TOKEN_EXPIRE.erro();
            }

            if(value instanceof Integer){
                return (long) (Integer)value;
            }else{
                return (Long)value;
            }
        }catch (JWTDecodeException e){
            if(throwable){
                throw  e;
            }else{
                return null;
            }
        }
    }
}
